package com.xinwangai.jingbai.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xinwangai.jingbai.mapper.MemberMapper;
import com.xinwangai.jingbai.pojo.BO.MemberBO;
import com.xinwangai.jingbai.pojo.DTO.MemberDTO;
import com.xinwangai.jingbai.pojo.DTO.UserDTO;
import com.xinwangai.jingbai.pojo.VO.MemberVO;
import com.xinwangai.jingbai.service.MemberService;
import com.xinwangai.jingbai.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 会员服务实现类
 *
 * @author guo.wenliang
 * @since 2025/6/19 17:12
 */
@Service
public class MemberServiceImpl implements MemberService {

    private final MemberMapper memberMapper;
    private final UserService userService;

    public MemberServiceImpl(MemberMapper memberMapper, UserService userService) {
        this.memberMapper = memberMapper;
        this.userService = userService;
    }

    @Override
    public Page<MemberVO> getMember(MemberDTO memberDTO) {
        PageHelper.startPage(memberDTO.getPageNum(), memberDTO.getPageSize(), true);
        Page<MemberBO> memberBOPage = memberMapper.getMember(memberDTO);

        // 将BO转换为VO
        List<MemberVO> memberVOList = memberBOPage.getResult().stream()
                .map(this::convertBOToVO)
                .collect(Collectors.toList());

        // 创建新的Page对象，包含转换后的VO数据
        Page<MemberVO> memberVOPage = new Page<>();
        BeanUtils.copyProperties(memberBOPage, memberVOPage);
        memberVOPage.addAll(memberVOList);

        return memberVOPage;
    }

    /**
     * 将MemberBO转换为MemberVO
     */
    private MemberVO convertBOToVO(MemberBO memberBO) {
        MemberVO memberVO = new MemberVO();
        BeanUtils.copyProperties(memberBO, memberVO);

        // 使用从数据库查询到的真实数据
        // 如果数据库中没有手机号和邮箱，使用空字符串作为默认值
        if (memberBO.getEmail() == null) {
            memberVO.setEmail("");
        }
        else {
            memberVO.setEmail(memberBO.getEmail());
        }
        if (memberBO.getPhone() == null) {
            memberVO.setPhone("");
        }
        else {
            memberVO.setPhone(memberBO.getPhone());
        }

        // 设置默认值（前端需要的字段）
        if (memberVO.getSkills() == null) {
            memberVO.setSkills("[]"); // 默认空技能数组的JSON字符串
        }
        if (memberVO.getStatus() == null) {
            memberVO.setStatus("active"); // 默认状态
        }


        return memberVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addMember(MemberDTO memberDTO) {
        try {
            // 如果提供了用户信息，先创建用户
            if (memberDTO.getUsername() != null && !memberDTO.getUsername().isEmpty()) {
                UserDTO userDTO = new UserDTO();
                userDTO.setUsername(memberDTO.getUsername());
                userDTO.setPassword(memberDTO.getPassword());
                // 将成员姓名写入用户昵称字段
                userDTO.setNickname(memberDTO.getMemberName());
                userDTO.setEmail(memberDTO.getEmail());
                userDTO.setPhone(memberDTO.getPhone());
                userDTO.setStatus(1); // 默认启用

                Long userId = userService.addUser(userDTO);
                if (userId == null) {
                    throw new RuntimeException("创建用户失败");
                }
                memberDTO.setUserId(userId);
            }

            // 如果没有用户ID，返回失败
            if (memberDTO.getUserId() == null) {
                throw new RuntimeException("必须提供用户信息或用户ID");
            }

            int result = memberMapper.addMember(memberDTO);
            if (result <= 0) {
                throw new RuntimeException("创建成员失败");
            }

            return true;
        }
        catch (Exception e) {
            e.printStackTrace();
            // 事务会自动回滚
            throw new RuntimeException("新增成员失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateMember(MemberDTO memberDTO) {
        try {
            int result = memberMapper.updateMember(memberDTO);
            UserDTO userDTO = memberDTO.getUserDTO();
            userService.updateUser(userDTO);
            return result > 0 ;
        }
        catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean deleteMember(Long id) {
        try {
            int result = memberMapper.deleteMember(id);
            return result > 0;
        }
        catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public MemberVO getMemberById(Long id) {
        try {
            MemberBO memberBO = memberMapper.getMemberById(id);
            if (memberBO != null) {
                return convertBOToVO(memberBO);
            }
            return null;
        }
        catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
